<script>
  import { goto } from '$app/navigation';
  import { acceptInvite } from '$lib/apiServer';

  import LogIn from '$lib/components/LogIn.svelte';

  let { data } = $props();

  let username = $state(''),
    password = $state('');
  let pending = false;
  let disabled = $derived(pending);

  async function onSubmit(event, inviteId) {
    event.preventDefault();
    pending = true;
    const response = await acceptInvite(inviteId, username, password);
    if (200 <= response.status && response.status < 300) {
      username = '';
      password = '';
      goto('/');
    }
    pending = false;
  }
</script>

{#await data.invite}
  <div class="invite-text">
    <p>Loading invitation…</p>
  </div>
{:then invite}
  <div class="invite-text">
    <p>Hi there! {invite.issuer} invites you to the conversation.</p>
  </div>
  <LogIn {disabled} bind:username bind:password onsubmit={(event) => onSubmit(event, invite.id)} />
{/await}
